package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.rediskey.RedisKeys;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
//@Transactional
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    public void saveVerifyCode(String phone, String code) {
        // 参数一:key=phone, 参数二:value=code, 参数三:有效时间5分钟, 参数四:有效时间单位
        redisTemplate.opsForValue().set(RedisKeys.VERIFY_CODE.getRedisKey(phone),code,Consts.VERIFY_CODE_VAI_TIME*60,TimeUnit.SECONDS);

    }
    @Override
    public void saveCount(String phone) {
        String verifyCode = getVerifyCode(RedisKeys.VERIFY_CODE.getRedisKey(phone));
        if (!StringUtils.hasLength(verifyCode)){
            // 存进 redis 中,时间为 30 秒
            redisTemplate.opsForValue().set(RedisKeys.FREQUENCY.getRedisKey(phone),String.valueOf(Consts.VERIFY_CODE_VAI_TIME),Consts.USER_INFO_TOKEN_VAI_TIME,TimeUnit.SECONDS);
        }
    }

    @Override
    public String getVerifyCode(String phone) {
        // 获取存进 redis 中的验证码
        return redisTemplate.opsForValue().get(phone);
    }

    @Override
    public void clickFrequency(String phone) {
        /**
         * 传参数手机号码过来,进入该方法,发送了5次,每进来一次 count - 1
         * when count < 0
         * thow 异常 发送频率过高,设置有效时间3分钟
         *
         */
/*        String count = redisTemplate.opsForValue().get(RedisKeys.FREQUENCY.getRedisKey(phone));
        int num = Integer.parseInt(count);
        redisTemplate.opsForValue().set(RedisKeys.FREQUENCY.getRedisKey(phone),String.valueOf(num-1));*/
        Long num = redisTemplate.opsForValue().decrement(RedisKeys.FREQUENCY.getRedisKey(phone), 1);
        if (num<0){
            throw new LogicException("你发送的频率过快,请在5分钟后再尝试");
        }
    }
}
